package com.ht.api.service;

import java.util.Date;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 获客Service
 * @author asq
 * @createTime 2025年4月3日 10:23:20
 */
@Slf4j
public class ExternalContactService {
	/** 接口ID：查询链接使用详情 */
	private static final long API_ID_LINK_QUERY = 1896836500184764416L;
	
	/**
	 * 新增用户时更新接粉相关数量
	 * @param ds 数据源
	 * @param state 渠道
	 * @param userid 用户ID
	 * @param createTime 加好友时间
	 */
	public static void updateInCnt(DataSource ds, String state, String userid, String createTime) {
		// 更新广告位相关接粉数量
		updateInCntByPosition(ds, state, createTime);
		
		// 更新关联表相关接粉数量
		Entity positionChannel = Db.createSqlParser("position_channel").where("state", state).findOne(ds);
		if (positionChannel != null) {
			String teamId = positionChannel.getStr("team_id");
			updateInCntByRel(ds, userid, 1, teamId, createTime);
		}
	}
	
	/**
	 * 用户入群时更新接粉相关数量
	 * @param ds 数据源
	 * @param groupChat 群详情（只包含本次入群的成员列表）
	 */
	public static void updateInCnt(DataSource ds, JSONObject groupChat) {
		String chatId = groupChat.getStr("chat_id");
		JSONArray memberList = groupChat.getJSONArray("member_list");
        if (memberList != null && !memberList.isEmpty()) {
            for (int i = 0; i < memberList.size(); i++) {
                JSONObject member = memberList.getJSONObject(i);

        		String state = member.getStr("state");
        		String createTime = member.getStr("join_time");
        		if (StrUtil.isNotBlank(state)) {
        			// 更新广告位相关接粉数量
        			updateInCntByPosition(ds, state, createTime);
        			
        			// 更新关联表相关接粉数量
        			Entity positionChannel = Db.createSqlParser("position_channel").where("state", state).findOne(ds);
        			if (positionChannel != null) {
        				String teamId = positionChannel.getStr("team_id");
        				updateInCntByRel(ds, chatId, 2, teamId, createTime);
        			}
        		}
            }
        }
	}
	
	/**
	 * 更新广告位相关接粉数量
	 * @param ds 数据源
	 * @param state 自定义渠道
	 * @param createTime 加入时间
	 */
	public static void updateInCntByPosition(DataSource ds, String state, String createTime) {
		try {
			if (StrUtil.isBlank(state)) {
				return;
			}
	
			// 查询渠道广告位
			Entity positionChannel = Db.createSqlParser("position_channel").where("state", state).findOne(ds);
			if (positionChannel == null) {
				return;
			}
			
			// 批量保存的数据集合
			DbList list = DbList.create();
			
			// 流量渠道数量维护
			String time = HtUtil.formatTimeString(createTime);
			String channelId = positionChannel.getStr("channel_id");
			Entity channel = Entity.create("fan_channel");
			channel.set("main_id", channelId);
			channel.set("in_cnt", 1);
			channel.set("first_in_time", time);
			channel.set("last_in_time", time);
			list.add(channel);
			
			// 广告位数量维护
			Entity position = Entity.create("position_channel");
			position.set("state", state);
			position.set("in_cnt", 1);
			position.set("first_in_time", time);
			position.set("last_in_time", time);
			list.add(position);
			
			// 接粉组数量维护
			Entity fanTeam = Entity.create("fan_team");
			fanTeam.setMainId(positionChannel.getStr("team_id"));
			fanTeam.set("in_cnt", 1);
			fanTeam.set("first_in_time", time);
			fanTeam.set("last_in_time", time);
			list.add(fanTeam);
			
			// 接粉统计表-渠道
			String date = getDayStr(createTime);
			Entity reportFanChannel = Entity.create("report_fan_channel");
			reportFanChannel.set("date", date);
			reportFanChannel.set("channel_id", channelId);
			reportFanChannel.set("in_cnt", 1);
			list.add(reportFanChannel);
			
			// 接粉统计表-广告位
			Entity reportPositionChannel = Entity.create("report_position_channel");
			reportPositionChannel.set("date", date);
			reportPositionChannel.set("position_id", position.getMainId());
			reportPositionChannel.set("in_cnt", 1);
			list.add(reportPositionChannel);
			
			// 接粉统计表-接粉组
			Entity reportFanTeam = Entity.create("report_fan_team");
			reportFanTeam.set("date", date);
			reportFanTeam.set("team_id", positionChannel.getStr("team_id"));
			reportFanTeam.set("in_cnt", 1);
			list.add(reportFanTeam);
			
			// 批量保存
			StreamLoadConfig streamConfig = DbConfig.getStreamLoadConfigByDataSource(ds);
			Db.insertBatchWithStream(streamConfig, list);
			
			// 拉取获客链接的点击数
			queryWxCustomerLinkStatistic(ds, positionChannel.getMainId(), positionChannel.getStr("in_type"));
		} catch (Exception e) {
			log.error("[ExternalContactService]更新接粉组相关的数量发生异常：{}", e.getMessage(), e);
		}
	}

	/**
	 * 更新关联表相关接粉数量
	 * @param ds 数据源
	 * @param relid 关联表的相关ID
	 * @param type 关联表类型
	 * @param teamId 接粉组ID
	 * @param createTime 进粉时间戳
	 */
	public static void updateInCntByRel(DataSource ds, String relid, int type, String teamId, String createTime) {
		DbList list = DbList.create();
		String time = HtUtil.formatTimeString(createTime);
		String date = getDayStr(createTime);
		
		// 接粉组的关联关系表的数量维护
		if (type == 1) {
			// 接粉客服组关联关系
			Entity fanServiceTeamRelation = Entity.create("fan_service_team_relation");
			fanServiceTeamRelation.set("team_id", teamId);
			fanServiceTeamRelation.set("userid", relid);
			fanServiceTeamRelation.set("in_cnt", 1);
			fanServiceTeamRelation.set("first_in_time", time);
			fanServiceTeamRelation.set("last_in_time", time);
			list.add(fanServiceTeamRelation);

			// 接粉统计表-客服组关联
			Entity reportServiceRelation = Entity.create("report_service_relation");
			reportServiceRelation.set("date", date);
			reportServiceRelation.set("rel_id", fanServiceTeamRelation.getMainId());
			reportServiceRelation.set("in_cnt", 1);
			list.add(reportServiceRelation);
		} else if (type == 2){
			// 接粉群聊组关联关系
			Entity fanChatTeamRelation = Entity.create("fan_chat_team_relation");
			fanChatTeamRelation.set("team_id", teamId);
			fanChatTeamRelation.set("chat_id", relid);
			fanChatTeamRelation.set("in_cnt", 1);
			fanChatTeamRelation.set("first_in_time", time);
			fanChatTeamRelation.set("last_in_time", time);
			list.add(fanChatTeamRelation);

			// 接粉统计表-客服组关联
			Entity reportChatRelation = Entity.create("report_chat_relation");
			reportChatRelation.set("date", date);
			reportChatRelation.set("rel_id", fanChatTeamRelation.getMainId());
			reportChatRelation.set("in_cnt", 1);
			list.add(reportChatRelation);
		} else if (type == 3){
			// 接粉平台客服组关联关系
			Entity fanUserTeamRelation = Entity.create("fan_user_team_relation");
			fanUserTeamRelation.set("team_id", teamId);
			fanUserTeamRelation.set("userid", relid);
			fanUserTeamRelation.set("in_cnt", 1);
			fanUserTeamRelation.set("first_in_time", time);
			fanUserTeamRelation.set("last_in_time", time);
			list.add(fanUserTeamRelation);

			// 接粉统计表-平台客服组关联
			Entity reportUserRelation = Entity.create("report_user_relation");
			reportUserRelation.set("date", date);
			reportUserRelation.set("rel_id", fanUserTeamRelation.getMainId());
			reportUserRelation.set("in_cnt", 1);
			list.add(reportUserRelation);
		}
		
		// 批量保存
		StreamLoadConfig streamConfig = DbConfig.getStreamLoadConfigByDataSource(ds);
		Db.insertBatchWithStream(streamConfig, list);
	}

	/**
	 * 根据时间戳计算yyyy-MM-dd格式的日期串
	 * @param createTime
	 * @return
	 */
	private static String getDayStr(String createTime) {
		long timestamp = Long.parseLong(createTime);
		return DateUtil.format(new Date(timestamp * 1000L), "yyyy-MM-dd");
	}
	
	/**
	 * 拉取获客链接的点击数
	 * @param ds 数据源
	 * @param positionId 广告位ID
	 * @param inType 获客类型
	 */
	private static void queryWxCustomerLinkStatistic(DataSource ds, String positionId, String inType) {
		if ("wx_customer_link".equals(inType)) {
			Entity wxCustomerLink = Db.createSqlParser("wx_customer_link").where("position_id", positionId).findOne(ds);
			if (wxCustomerLink != null) {
				String appid = wxCustomerLink.getStr("appid");
				Long startTime = wxCustomerLink.getLong("start_time");
				if (startTime == null) {
					startTime = DateUtil.currentSeconds();
				}
				DateTime date1DaysAgo = DateUtil.offsetDay(DateUtil.date(), -1);
				long timestamp1DaysAgo = date1DaysAgo.getTime() / 1000;
				startTime = Math.min(startTime, timestamp1DaysAgo);
				long end_time = DateUtil.currentSeconds();

				// 查询企微接口
				JSONObject param = JSONUtil.createObj();
				param.set("link_id", wxCustomerLink.getStr("link_id"));
				param.set("start_time", startTime);
				param.set("end_time", end_time);				
				String str = OpenUtil.call(appid, API_ID_LINK_QUERY, JSONUtil.createObj());
				JSONObject obj = JSONUtil.parseObj(str);
				if (obj.getInt("errcode") == 0) {
					Entity link = Entity.create("wx_customer_link");
					link.set("appid", appid);
					link.set("state", wxCustomerLink.getStr("state"));
					link.set("click_link_customer_cnt", obj.getStr("click_link_customer_cnt"));
					link.set("new_customer_cnt", obj.getStr("new_customer_cnt"));
					link.set("start_time", end_time);
					Db.insert(ds, link);
				} else {
					throw new HtException("查询链接使用详情企微接口返回错误：" + obj.getStr("errmsg"));
				}
			}
		}
	}
}
